package com.mwj.gulimall.prodict.service.impl;

import com.mwj.common.to.SpuBoundTo;
import com.mwj.common.to.SpuReductionTo;
import com.mwj.common.utils.R;
import com.mwj.gulimall.prodict.entity.*;
import com.mwj.gulimall.prodict.feign.CouponFeignService;
import com.mwj.gulimall.prodict.service.*;
import com.mwj.gulimall.prodict.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mwj.common.utils.PageUtils;
import com.mwj.common.utils.Query;

import com.mwj.gulimall.prodict.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService attrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //TODO 高级部分完善
    @Transactional//事务
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
         //1.保存 spu基本信息 pms_sku_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpInfo(spuInfoEntity);

        //2.保存描述图面 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDes(descEntity);
        //3保存sup图片集 pms_spu_images
        List<String> images = vo.getImages();//图片
        imagesService.saveImages(spuInfoEntity.getId(),images);//根据id存入图片
        //4。保存spu的规格参数  pms_sku_sale_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();//规格参数的vo
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {//遍历规格参数绑定的产品信息等
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());//属性id
            AttrEntity byId = attrService.getById(attr.getAttrId());//查询商品信息
            valueEntity.setAttrName(byId.getAttrName());//属性名
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());//转数组
        attrValueService.saveProductAttr(collect);
        //5.保存spu的积分信息：sms_spu_bounds
        // 6.4 sku的优惠，满减条件：gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() !=0){
            log.error("远程保存spu积分信息失败");
        }
        List<Skus> skus = vo.getSkus();
        //遍历sku的信息
        if (skus!=null || skus.size()>0){

            skus.forEach(item->{//遍历sku信息
                String defaultImg = "";
                for (Images images1 :item.getImages()){
                    if(images1.getDefaultImg()==1){
                        defaultImg =images1.getImgUrl();
                    }
                }
                SkuInfoEntity InfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,InfoEntity);
                InfoEntity.setBrandId(spuInfoEntity.getBrandId());
                InfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                InfoEntity.setSaleCount(0L);
                InfoEntity.setSkuDefaultImg(defaultImg);
                //6.1 sku的基本信息：pms_spu_info
                skuInfoService.saveSkuIfo(InfoEntity);
                Long skuId = InfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {//遍历图片
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(etity->{
                    //返回为tru就需要，false就是剔除
                    return !StringUtils.isEmpty(etity.getImgUrl());
                }).collect(Collectors.toList());
                //6.2 sku图片信息 pms_spu_images
                skuImagesService.saveBatch(imagesEntities);
                //TODO 没有选中的图片不进行保存进数据库
                // 6.3 sku销售属性 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 6.4 sku的优惠，满减条件：gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SpuReductionTo spuReductionTo = new SpuReductionTo();
                BeanUtils.copyProperties(item,spuReductionTo);
                spuReductionTo.setSkuId(skuId);
                if (spuReductionTo.getFullCount()>0 || spuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){

                    R r1 = couponFeignService.saveSkuReduction(spuReductionTo);
                    if (r1.getCode() !=0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
        // 6.保存当前sku对应的sku信息 ->sms_spu_bounds
        //6.1 sku的基本信息：pms_spu_info
        //6.2 sku图片信息 pms_spu_images
        // 6.3 sku销售属性 pms_sku_sale_attr_value
        // 6.4 sku的优惠，满减条件：gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
    }

    @Override
    public void saveBaseSpInfo(SpuInfoEntity spuInfoEntity) {
        baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status) && !"0".equalsIgnoreCase(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


}